'use strict';

import React from 'react'
import PropTypes from 'prop-types'
import { withStyles } from '@material-ui/core/styles'
import {
  TextField,
  Button,
  CircularProgress,
  FormControlLabel,
  Checkbox,
  Snackbar,
  Badge,
} from '@material-ui/core'
import { NavLink } from 'react-router-dom'

import DiagnosisIcon from '@material-ui/icons/AccountCircleRounded'
import NewIcon from '@material-ui/icons/AddCircleRounded'
import HistoryIcon from '@material-ui/icons/HistoryRounded'

const electron = window.require('electron')
const uuid = require('uuid/v4')


const styles = theme => ({
  menuItem: {
    color: 'inherit',
    margin: '24px 6px'
  },
  icon: {
    fontSize: 32,
  },
  hisIcon: {
    marginTop: 8,
    fontSize: 32,
  },
  newIcon: {
    fontSize: 32,
    color: '#D7DADF'
  },
  active: {
    color: '#D7DADF'
  },
  badge: {
    margin: '16px 0',
  }
});

class NavBar extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      patients: []
    }
  }
  
  componentDidMount() {
    electron.ipcRenderer.on('New', () => {
      this.newDiagnosis()
    })
    electron.ipcRenderer.on('Save', () => {
      // this.newDiagnosis()
    })
    electron.ipcRenderer.on('Close', () => {
      this.closeDiagnosis()
    })
    this.updateName()
  }

  updateName() {
    const patients = [];
    for (let k = 0; k < this.state.patients.length; k += 1) {
      let state = electron.ipcRenderer.sendSync('getPatient', this.state.patients[k]._id)
      if (state === null) {
        patients.push(this.state.patients[k])
      } else {
        patients.push(state)
      }
    }
    this.setState({
      patients: patients
    })
    setTimeout(() =>  this.updateName(), 1000)
  }

  newDiagnosis() {
    let { patients } = this.state
    if (patients.length > 9) return;
    const _id = uuid()
    patients.push({
      _id: _id
    })
    this.setState({ 
      patients: patients
    })
    setTimeout(() => this.props.history.push(`/diagnosis/${_id}`), 200)
  }

  closeDiagnosis() {
    let _id = this.props.history.location.pathname.split('/')[2]
    const { patients } = this.state
    let ps = []
    patients.map((patient) => {
      if (patient._id !== _id) {
        ps.push(patient)
      }
    })
    if (ps.length === 0) {
      this.props.history.push('/')
    } else {
      this.props.history.push(`/diagnosis/${ps[0]._id}`)
    }
    this.setState({
      patients: ps
    })
  }
  
  render() {
    const { classes } = this.props
    const { patients } = this.state
    return (
      <div>
        <NavLink to='/' className={classes.menuItem} >
          <NewIcon className={classes.newIcon} onClick={() => this.newDiagnosis()} />
        </NavLink>
        {
          patients.map((patient) => (
            <NavLink
              exact
              key={`menu-${patient._id}`}
              to={`/diagnosis/${patient._id}`}
              className={classes.menuItem}
              activeClassName={classes.active}
              onDoubleClick={() => this.closeDiagnosis()}
            >
              <Badge
                badgeContent={patient && patient.state && patient.state.fullname && patient.state.fullname.label && patient.state.fullname.label.substr(0, 1) || ''}
                className={classes.badge} color={patient.saved ? 'default' : 'secondary'}
              >
                <DiagnosisIcon className={classes.icon} />
              </Badge>
            </NavLink>
          ))
        }
        <NavLink to='/diagnosisHistory' className={classes.menuItem} activeClassName={classes.active}>
          <HistoryIcon className={classes.hisIcon} />
        </NavLink>
      </div>
    )
  }
}

NavBar.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(NavBar);